import sys
from xml.dom import minidom

import pygame
import utils
import widget

class TileMapView(widget.Widget):
	"""
	A tiled view of our world.
	"""
	def __init__(self, left, top, width, height, world):
		widget.Widget.__init__(self, left, top, width, height)

		self.world = world
		
		# the top, left tile to draw
		self.topTile = 0
		self.leftTile = 0
		
		# how many tiles can we draw?
		self.widthInTiles = width / self.world.map.tileWidth
		self.heightInTiles = height / self.world.map.tileHeight

		# what tiles are visible?
		self.visibleX = []
		self.visibleY = []

		self.highlightRect = None
		
		self.mapSurface = pygame.Surface((width, height), 0, 32)
		self.updateMapSurface()

	def setHighlightRect(self, x, y):
		self.highlightRect = (x * 36, y * 36, 36, 36)

	def getTile(self, x, y):
		if x in range(self.world.map.width) and y in range(self.world.map.height):
			return self.world.map.data[x, y]
		else:
			return -1

	def updateMapSurface(self):
		self.mapSurface.fill((255, 0, 255))

		for y in range(self.heightInTiles):
			for x in range(self.widthInTiles):
				# if the tile is set, draw it
				tile = self.getTile(x + self.leftTile, y + self.topTile)
				if tile != -1:
					self.mapSurface.blit(self.world.map.tiles[tile].image, (x * self.world.map.tileWidth + self.rect.left, y * self.world.map.tileHeight + self.rect.top))
	
	def onKeyDown(self, event):
		handled = False

		if event.key == pygame.K_KP2:
			self.topTile += 1
			handled = True
		if event.key == pygame.K_KP4:
			self.leftTile -= 1
			handled = True
		if event.key == pygame.K_KP6:
			self.leftTile += 1
			handled = True
		if event.key == pygame.K_KP8:
			self.topTile -= 1
			handled = True
	
		if handled:
			self.updateMapSurface()

		return handled

	def draw(self, screen):
		screen.blit(self.mapSurface, (0, 0))

		for currentItem in self.world.itemList:
			self.drawEntity(screen, currentItem)
		for currentUnit in self.world.unitList:
			self.drawEntity(screen, currentUnit)

		if not self.highlightRect is None:
			pygame.draw.rect(screen, (255, 255, 0), self.highlightRect, 3) 

	def drawEntity(self, screen, entity):
		screen.blit(entity.image, ((entity.x - self.leftTile) * self.world.map.tileWidth, (entity.y - self.topTile) * self.world.map.tileHeight))
